package com.cskt.controller;

/**
 * @author mo
 * @Description: 登录控制器
 * @date 2020-09-02 20:51
 */

import com.cskt.shiro.JwtUtil;
import com.cskt.util.JsonUtil;
import com.cskt.util.MD5.MD5;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.vo.ReturnResult;
import com.cskt.common.vo.TokenVO;
import com.cskt.entity.User;
import com.cskt.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * @author mo
 * @Description: 登录控制器
 * @date 2020-09-22 15:58
 */
@Api(tags = "登录相关控制器")
@RestController
@RequestMapping(value = "/api")

public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private   StringRedisTemplate stringRedisTemplate;
    private static  final Logger log= LoggerFactory.getLogger(LoginController.class);
    @ApiOperation(value = "登陆接口",response =ReturnResult.class,httpMethod = "POST",produces =MediaType.APPLICATION_JSON_VALUE
            , protocols ="HTTP")

    @RequestMapping(value = "/dologin", produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.POST)
    public ReturnResult login(@ApiParam(name = "name", value = "登录用户名")
                              @RequestParam("name") String userCode,
                              @ApiParam(name = "password", value = "登录密码")
                              @RequestParam("password") String userPassword,
                              HttpServletRequest request) {
        System.out.println("123213");
        if (StringUtils.isEmpty(userCode) || StringUtils.isEmpty(userPassword))
        {
//当用户编码或用户密码为空的时候
            return ReturnResult.error(ErrorCodeEnum.AUTH_PARAMETER_ERROR);
        }
        User user = userService.findUserByUserCode(userCode);
        if (user == null) {
            //不建议这么返回 ,我们在账号用户名或者密码输入错误时 ，放回模糊提示“譬如密码或者用户输入错误”
            return ReturnResult.error(ErrorCodeEnum.AUTH_UNKNOWN);
        }
        if (!MD5.getMd5(userPassword, 32).equals(user.getUserPassword())) {
//当密码不匹配时返回错误信息
            return ReturnResult.error(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }
        String jwtToken = null;
        try {
            jwtToken = JwtUtil.sign(userCode, MD5.getMd5(userPassword, 32));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        TokenVO tokenVo = new TokenVO(jwtToken, System.currentTimeMillis() + 2 *
                3600 * 1000, System.currentTimeMillis());
//将用户信息存储到redis中，以jwtToken做为key，跟需求有一些出入，不区分移动端和PC端
        try {
            stringRedisTemplate.opsForValue().set(jwtToken, JsonUtil.objectToJsonString(user) ,2, TimeUnit.HOURS);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(),e);
            //序列化时出现异常
            return  ReturnResult.error(ErrorCodeEnum.ERROR_CALLING_THIRD_PARTY_SERVICE);
        }

        return ReturnResult.ok(tokenVo);
    }
}